﻿namespace PropOnline.Models.Validation
{
    using System;
    using System.Collections.Generic;
    using System.ComponentModel.DataAnnotations;
    using System.Globalization;
    using System.Linq;
    using System.Web.Mvc;
    using PropOnline.Models;
    using PropOnline.ViewModels.Tasacion;

    [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = false)]
    public class RequiredIfAttribute : ValidationAttribute, IClientValidatable
    {
        private string otherProperty;        
        private Mode mode;

        public RequiredIfAttribute(string otherProperty, Mode mode)
        {
            this.otherProperty = otherProperty;
            this.mode = mode;
        }

        public enum Mode
        {
            OtherFieldBlank = 0,
            OtherFieldFilled
        }

        public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
        {            
            var rule = new ModelClientValidationRule
            {
                ValidationType = "requiredif",
                ErrorMessage = this.ErrorMessageString         
            };
                                        
            rule.ValidationParameters.Add("otherfield", this.otherProperty);
            rule.ValidationParameters.Add("mode", (int)this.mode);

            yield return rule;
        }

        protected override ValidationResult IsValid(object value, ValidationContext validationContext)
        {
            if (value == null)
            {
                var property = validationContext.ObjectInstance.GetType().GetProperty(this.otherProperty);

                if (property.PropertyType != typeof(string) && property.PropertyType != typeof(string))
                {
                    throw new InvalidOperationException("The RequiredIfValidator can only be used with string properties.");
                }

                var propertyValue = property.GetValue(validationContext.ObjectInstance, null);
                
                if (propertyValue == null)
                {
                    return new ValidationResult(this.ErrorMessageString);
                }
            }

            return ValidationResult.Success;            
        }
    }
}